﻿define('scheduleTemplate',
    ['ko', 'formActions', 'scheduleTemplateItem'],
 function (ko, formActions, scheduleTemplateItem) {
     var scheduleTemplate = function (obj, providerId) {
         var self = this;

         self.defaultColor = "#d3d3d3";
         self.guidEmpty = "00000000-0000-0000-0000-000000000000";
         self.weekSize = 7;

         self.templateName = "scheduleTemplate";
         self.deleteController = "/api/ScheduleTemplates/Delete/";
         self.id = ko.observable();
         self.name = ko.observable().extend({ required: "Name is required" });
         self.timeForOnePerson = ko.observable().extend({ required: "Field is required" });
         self.createdOn = ko.observable();
         self.forDelete = ko.observable(false);
         
         self.start1 = ko.observable();
         self.start1.hasError = ko.observable(true);
         self.start1.validationMessage = ko.observable();

         self.start2 = ko.observable();
         self.start2.hasError = ko.observable(true);
         self.start2.validationMessage = ko.observable();

         self.start3 = ko.observable();
         self.start3.hasError = ko.observable(true);
         self.start3.validationMessage = ko.observable();
         
         self.start4 = ko.observable();
         self.start4.hasError = ko.observable(true);
         self.start4.validationMessage = ko.observable();
         
         self.start5 = ko.observable();
         self.start5.hasError = ko.observable(true);
         self.start5.validationMessage = ko.observable();

         self.start6 = ko.observable();
         self.start6.hasError = ko.observable(true);
         self.start6.validationMessage = ko.observable();
         
         self.start7 = ko.observable();
         self.start7.hasError = ko.observable(true);
         self.start7.validationMessage = ko.observable();

         self.scheduleTemplateItems = ko.observableArray([]);
         
         self.providerId = ko.observable();
         if (self.providerId != null) self.providerId(providerId);

         self.load = function (d) {
             self.id(d.id);
             self.name(d.name);
             self.timeForOnePerson(d.timeForOnePerson);
             self.providerId(d.providerId);
             self.createdOn(d.createdOn);
             if (d.start1!=null) self.start1(d.start1.substring(0, 5));
             if (d.start2 != null) self.start2(d.start2.substring(0, 5));
             if (d.start3 != null) self.start3(d.start3.substring(0, 5));
             if (d.start4 != null) self.start4(d.start4.substring(0, 5));
             if (d.start5 != null) self.start5(d.start5.substring(0, 5));
             if (d.start6 != null) self.start6(d.start6.substring(0, 5));
             if (d.start7 != null) self.start7(d.start7.substring(0, 5));
         };
         
         if (obj != null) self.load(obj);

         var loadScheduleTemplateItems = function (data, day, scheduleTypes) {
             var items = $.grep(data, function(item) {
                 return (item.dayNumber == day);
             });

            
             var ar = ko.observableArray([]);
             
             $.each(items, function() {
                 var sti = this;
                 var st = $.grep(scheduleTypes, function (c) {
                     return (c.id() == sti.scheduleTypeId);
                 });
                 var color;
                 
                 if (st.length == 1) color = st[0].color();
                 else color = self.defaultColor;
                 var o = new scheduleTemplateItem(sti, color);
                 ar.push(o);
             });
             
             return ar;
         };

         self.loadScheduleTemplateItems = function(scheduleTemplateId, scheduleTypes, callback) {
             SendAjax("/api/ScheduleTemplates/GetByScheduleTemplate", { scheduleTemplateId: scheduleTemplateId }, function (data) {
                 self.scheduleTemplateItems.removeAll();
                 for (var j = 0; j < self.weekSize; j++) {
                     var arr = loadScheduleTemplateItems(data, (j + 1), scheduleTypes);
                     self.scheduleTemplateItems.push(arr);
                 }
                 if(callback!=null) callback();
             });
         };

         self.ApplyColors = function (selectedScheduleType) {

             for (var i = 0; i < self.weekSize; i++) {
                 $.each(self.scheduleTemplateItems()[i](), function () {
                     if ($("#ulItems" + i + " li[recordid='" + this.id() + "']").hasClass("ui-selected")) {
                         this.color(selectedScheduleType().color());
                         this.scheduleTypeId(selectedScheduleType().id());
                         $("#ulItems" + i + " li[recordid='" + this.id() + "']").removeClass("ui-selected");
                     }
                 });
             }
         };

         self.ClearColorsAll = function () {
             for (var i = 0; i < self.weekSize; i++) {
                 $.each(self.scheduleTemplateItems()[i](), function () {
                     this.scheduleTypeId(self.guidEmpty);
                     this.color(self.defaultColor);
                 });
             }
             $(".ulItems li").removeClass("ui-selected");
         };

         self.ClearColorsSelected = function () {
             for (var i = 0; i < self.weekSize; i++) {
                 $.each(self.scheduleTemplateItems()[i](), function () {
                     if ($("#ulItems" + i + " li[recordid='" + this.id() + "']").hasClass("ui-selected")) {
                         this.scheduleTypeId(self.guidEmpty);
                         this.color(self.defaultColor);
                         $("#ulItems" + i + " li[recordid='" + this.id() + "']").removeClass("ui-selected");
                     }
                 });
             };
         };
         

         
         var formAction = new formActions("/api/ScheduleTemplates/", self);
         self.validation = function () { formAction.validation(); };
         self.clearValidation = function () { formAction.clearValidation(); };
         /*self.save = function (parent, dlg) {
             formAction.save(parent, dlg);
         };*/

         self.validate = function() {
             
             if (self.name.hasError()) return false;
             if (self.timeForOnePerson.hasError()) return false;
             //todo validate numeric
             var maskInteger = /^\d+$/;
             if (maskInteger.test(self.timeForOnePerson())==false) {
                 self.timeForOnePerson.hasError(true);
                 self.timeForOnePerson.validationMessage("Is numeric");
                 return false;
             }
              if (self.checkStart(self.start1) == false) return false;
           if (self.checkStart(self.start2) == false) return false;
           if (self.checkStart(self.start3) == false) return false;
           if (self.checkStart(self.start4) == false) return false;
           if (self.checkStart(self.start5) == false) return false;
           if (self.checkStart(self.start6) == false) return false;
           if (self.checkStart(self.start7) == false) return false;
             
            
             return true;
         };

        
         self.checkStart = function(start) {
             console.log("Check");
             if (start()!=null && start() != "") {
                 var maskTime = /^(([0-1][0-9]|2[0-3]|[0-9])|([0-1][0-9]|2[0-3]|[0-9])(:|h)[0-5]?[0-9]?)$/;
                 var result = maskTime.test(start());
                 if (result == false) {
                     start("");
                     start.hasError(true);
                     return false;
                 }
             }
         };

         self.save = function (parent, dlg,scheduleTypes, close) {
             var isValid = self.validate();
             
             if (isValid) {
                 self.items = new Array();
                 for (var i = 0; i < self.weekSize; i++) {
                     $.each(self.scheduleTemplateItems()[i](), function () {
                         self.items.push(this);
                     });
                 };


                 var frm = ko.toJSON(self, null, 2);

                 
                // console.log(ko.toJSON(self, null, 2));

                 $.ajax({
                     type: "POST",
                     url: "/Medora.Web" + "/api/ScheduleTemplates/",
                     contentType: "application/json",
                     data: frm,
                     success: function (data) {
                         self.load(data);

                         var existsItems = (self.scheduleTemplateItems().length > 0);
                         if (existsItems == false) {
                             self.loadScheduleTemplateItems(self.id(), scheduleTypes);

                             toastr.success("Data saved succesfully");
                             return false;
                         } else {

                             if (close == true) {
                                 parent.RefreshGrid();
                                 dlg.close();
                             }
                             toastr.success("Data saved succesfully");
                             return true;
                         }

                     },
                     error: function (response) {
                         if (response.status == 400) {
                             self.validation(response.responseText);
                         }
                         return false;
                     }
                 });
             }
             
         };
     };

     return scheduleTemplate;

 });